package com.hundsun.yr.universal.p2p.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.utils.HsStringUtils;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.utils.RegularUtils;
import com.hundsun.yr.universal.library.utils.SpannableStringBuilderUtils;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSEditText;
import com.hundsun.yr.universal.p2p.bean.BankAccountBeen;
import com.hundsun.yr.universal.p2p.bean.MineInvestProtocolBean;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.bean.enums.EnumBank;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.RechangeNewActivity;
import com.hundsun.yr.universal.p2p.ui.activity.RechargeSuccess;
import com.hundsun.yr.universal.p2p.ui.activity.WebActivity;
import com.hundsun.yr.universal.p2p.ui.activity.WebOpenAccountActivity;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseFragment;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;
import com.hundsun.yr.universal.p2p.widget.ValidateButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import de.greenrobot.event.EventBus;


/**
 * @version V1.0
 * @Title: RechangeQuickFragment.java
 * @Description: 充值--快捷充值
 * @date 2016-1-15 下午3:55:07
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class RechangeQuickFragment extends BaseFragment implements OnClickListener, InitializeView {

    /**
     * 提交按钮
     **/
    private HSButton btn_submit = null;
//    private ValidateButton btn_vcode = null;
    /**
     * 银行卡logo
     **/
    private ImageView iv_logo = null;
    /**
     * 选中银行卡
     **/
    private TextView tv_bank = null;
    /**
     * 预留手机号
     **/
    private TextView tv_phone = null;
    /**
     * 验证码
     **/
//    private HSEditText et_vcode = null;
    /**
     * 金额输入框
     **/
    private HSEditText et_money = null;
    /**
     * 银行卡item布局
     **/
    private LinearLayout linear_bankcard;

    /**
     * 请求接口
     **/
    private RequestPresenter mPresenter = null;
//    private BrowserLayout mBrowserLayout = null;
    /**
     * 预留银行卡电话
     **/
    private String phone = "";
    /**
     * 银行卡号
     **/
    private String cardNo = null;
    /**
     * 验证码
     */
    private String vCode = null;

    /**
     * 充值金额
     */
    private String amount = null;
    private String zwgt_data;

    private TextView tv_support_bank_and_limit = null;
    private BankAccountBeen bankAccountBeen;

    /**
     * 序列号
     **/
//	private String serialNumber="";
    @Override
    protected void onFirstUserVisible() {
        // TODO Auto-generated method stub
        mPresenter = new InitializePresenterImpl(mContext, this);

    }

    @Override
    protected void onUserVisible() {
    }

    @Override
    protected void onUserInvisible() {
        // TODO Auto-generated method stub

    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void initViewsAndEvents() {
        // TODO Auto-generated method stub
        tv_bank = findView(R.id.tv_bank);
        iv_logo = findView(R.id.iv_logo);

        cardNo = sharedPreferences.getShareProf(UserInfo.BANKCARD);

        String bankName = getString(R.string._bankname, sharedPreferences.getShareProf(UserInfo.BANKCARDNAME),
                HsStringUtils.subString(cardNo, cardNo.length() - 4, cardNo.length()));
        if (cardNo.length() > 4) {
            tv_bank.setText(SpannableStringBuilderUtils.colorSpan(bankName,
                    getResources().getColor(R.color.text_cc), bankName.length() - 8, bankName.length()));
        } else {
            tv_bank.setText(bankName);
        }

//        tv_bank.setText(sharedPreferences.getShareProf(UserInfo.BANKCARD));
        iv_logo.setImageResource(EnumBank.getbankLogo(sharedPreferences.getShareProf(UserInfo.BANKCARDNAME)));

        et_money = findView(R.id.et_money);
        tv_phone = findView(R.id.tv_phone);
        if (sharedPreferences.getShareProf(UserInfo.BANKMOBILE) != null) {
            tv_phone.setText(getString(R.string.send_vcode_to_phone, CommTool.encodPhone(sharedPreferences.getShareProf(UserInfo.BANKMOBILE))));
        } else {
            tv_phone.setText("");
        }

//        et_vcode = findView(R.id.et_vcode);
        linear_bankcard = findView(R.id.linear_bankcard);
        btn_submit = findView(R.id.btn_submit);
        btn_submit.setOnClickListener(this);
        //发送验证码
//        btn_vcode = findView(R.id.btn_vcode);
//        btn_vcode.init(false, "UpdateJXReservedPhoneActivity");
//        btn_vcode.setOnClickListener(this);

        linear_bankcard.setOnClickListener(this);
//        mBrowserLayout = findView(R.id.common_web_browser_layout);

        tv_support_bank_and_limit = findView(R.id.tv_support_bank_and_limit);
        tv_support_bank_and_limit.setOnClickListener(this);
        //添加请求头
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        HashMap<String, String> hearder = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_trade) +
                TaskConstants.TASK_IMTRECHARGELIST, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
        //进行网络请求
//        mBrowserLayout.loadUrl(getString(R.string.root_url_test) + getString(R.string.h5_trade) + TaskConstants.TASK_IMTRECHARGELIST,hearder);
//        mBrowserLayout.hideBrowserController();
    }

    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.frag_rechange_quick;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub
    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.linear_bankcard:
/*                if (sharedPreferences.getShareProf(UserInfo.BANKCARD) == null){

                }*/
/*                String bindCard = sharedPreferences.getShareProf(UserInfo.BANKCARD);
                Bundle bundle = new Bundle();
                bundle.putString("bindCard", bindCard);
                readyGo(MineBankCardActivity.class, bundle);*/
                break;

            case R.id.btn_submit://充值
                phone = tv_phone.getText().toString();
                validate();
                break;

//            case R.id.btn_vcode://验证码
//                //请求验证码
//                try {
//                    phone = sharedPreferences.getShareProf(UserInfo.BANKMOBILE);
//                }catch (Exception e){
//                    phone = "";
//                }
//
//                sendVcode(phone);
//                break;

            case R.id.tv_support_bank_and_limit://快捷充值限额
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_trade) +
                        TaskConstants.TASK_LMTRECHARGELIST, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap = new HeaderMap();
                headerMap.setMap(hearder);
                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, "快捷充值限额");
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, getString(R.string.root_h5_url_test) + getString(R.string.h5_trade) + TaskConstants.TASK_LMTRECHARGELIST);
                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebActivity.class, bundle);
                break;
        }

    }

    /**
     * 本地验证
     */
    public void validate() {
        //手机号验证
        if (TextUtils.isEmpty(phone)) {
            showToast(R.string.input_bind_mobile);
            return;
        }

        if (phone.isEmpty()) {
            showToast(getString(R.string.empty_phone_number));
            return;
        }

        //验证充值金额
        if (TextUtils.isEmpty(et_money.getText())) {
            showToast(R.string.input_rechange_money);
            return;
        }

        if (et_money.getText().toString().endsWith(".")) {
            showToast(R.string.input_correct_number);
            return;
        }

        if (!(sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT) != null && TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT), "YES"))){
            showToast(getString(R.string.open_account));
            return;
        }

        if (!sharedPreferences.getShareProf(UserInfo.IF_PAYPWD).equals("YES")){
            showToast(R.string.set_paypwd_yet);
            return;
        }

        if (MathUtils.compare(et_money.getText().toString(), "100") < 0) {
            showToast(R.string.min_rechange_money);
            return;
        }

//        vCode = et_vcode.getText().toString();
        amount = et_money.getText().toString();

//        //验证码
//        if (TextUtils.isEmpty(vCode)){
//            showToast(getString(R.string.input_mobile_code));
//            return;
//        }

        //开始请求网络进行快捷充值
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();

        try {
            map.put("amount", amount);
//            map.put("code", vCode);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
        mPresenter.loadingData(TaskConstants.TASK_RECHARGEPAGE, getString(R.string.root_url_test) + getString(R.string.api_trade_test) + TaskConstants.TASK_RECHARGEPAGE,
                Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_trade_test) + TaskConstants.TASK_RECHARGEPAGE,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    @SuppressWarnings("deprecation")
    @Override
    public <T> void initializeViews(String task_name, T data) {
        if (TextUtils.equals(task_name, TaskConstants.TASK_RECHARGEPAGE)) {

            MineInvestProtocolBean rechargeBean = (MineInvestProtocolBean) data;

            zwgt_data = BaseRequestTool2.getFormatedDateString();
            HashMap<String, String> hearder1 = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                    TaskConstants.TASK_RECHARGERST, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
            HeaderMap headerMap1 = new HeaderMap();
            headerMap1.setMap(hearder1);
            Bundle bundle1 = new Bundle();
            bundle1.putString(BaseWebActivity.BUNDLE_KEY_URL, rechargeBean.html);
            bundle1.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap1);
//            bundle1.putSerializable(BaseWebActivity.BUNDLE_KEY_TITLE, zwgt_data);
            bundle1.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
            readyGo(WebOpenAccountActivity.class, bundle1);

//            //刷新设置界面数据
//            EventBus.getDefault().post(new EventCenter(Constants.EVENT_REFRESH_DATA));
//            //刷新即信接口
//            mPresenter.loadingData(TaskConstants.TASK_BANK_ACCOUNT, getString(R.string.root_url_test) + getString(R.string.api_user_test) +
//                    TaskConstants.TASK_BANK_ACCOUNT, Constants.EVENT_BEGIN, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test)
//                    + TaskConstants.TASK_BANK_ACCOUNT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
        } else if (TextUtils.equals(TaskConstants.TASK_BANK_ACCOUNT, task_name)) {
            //查询托管账户信息，更新ui
            bankAccountBeen = (BankAccountBeen) data;
            /**保存可用余额**/
            if (bankAccountBeen.availBal != null && !bankAccountBeen.availBal.isEmpty()) {
                sharedPreferences.putShareProf(UserInfo.CAN_USE_MONEY, bankAccountBeen.availBal);
            }

            if ((((RechangeNewActivity) getActivity()).MINERECHARGE)) {
                //跳转充值冲个界面
                Bundle bundle = new Bundle();
                bundle.putString("RECHAGE_AMOUNT", amount);
                readyGo(RechargeSuccess.class, bundle);
            }

            getActivity().finish();
        }
    }


    @Override
    public <T> void initializeError(String task_name, T data) {
        // TODO Auto-generated method stub

    }

    /**
     * 验证手机号码，发送验证码
     *
     * @param phone
     */
//    private void sendVcode(String phone) {
//        zwgt_data = BaseRequestTool2.getFormatedDateString();
//        JSONObject map = new JSONObject();
//
//        //检查是否输入手机号
//        if (TextUtils.isEmpty(phone)) {
//            showToast(R.string.input_bind_mobile);
//            return;
//        }
//
//        //检查手机号格式
//        if (!RegularUtils.isPhoneNum(phone)) {
//            showToast(R.string.input_format_mobile);
//            return;
//        }
//
////        btn_vcode.setCountdown();
//
//        try {
//            map.put("srvtxcode", "directRechargeOnline");
//            map.put("phone", phone);
////            map.put("channel","0");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
//        mPresenter.loadingData(TaskConstants.TASK_SMS_APPLY, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_pub_test) + TaskConstants.TASK_SMS_APPLY, Constants.EVENT_DATA,
//                jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_pub_test) + TaskConstants.TASK_SMS_APPLY, sharedPreferences
//                        .getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
//    }
}

